package com.cennavi.minemapdemo.activity.ue;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.cennavi.minemapdemo.R;
import com.cennavi.minemapdemo.activity.BaseActivty;
import com.cennavi.minemapdemo.util.Config;
import com.cennavi.minemapdemo.util.DensityUtil;
import com.cennavi.minemapdemo.util.RandomUtil;
import com.minedata.minemap.MinemapAccountManager;
import com.minedata.minemap.camera.CameraPosition;
import com.minedata.minemap.camera.CameraUpdateFactory;
import com.minedata.minemap.geometry.LatLng;
import com.minedata.minemap.map.MapView;
import com.minedata.minemap.map.MineMap;
import com.minedata.minemap.overlay.MarkerLayer;
import com.minedata.minemap.overlay.MarkerLayerOptions;
import com.minedata.minemap.overlay.Polygon;
import com.minedata.minemap.overlay.PolygonOptions;
import com.minedata.minemap.overlay.Polyline;
import com.minedata.minemap.overlay.PolylineOptions;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;


public class DistanceUtilActivty extends BaseActivty implements MineMap.OnMapClickListener{

    //地图视图
    private MapView mapView;
    //地图操作类
    private MineMap mineMap;
    private Context mContext;

    private TextView btn_distance;
	private TextView btn_area;
	private TextView value;

    private MarkerLayer currentlocation = null;
    private MarkerLayerOptions.MarkerItem markerItem = null;

    private LatLng center;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        MinemapAccountManager.getInstance(this, Config.MAP_TOK, Config.OFFLINE_TOK, Config.MAP_ID);

        setContentView(R.layout.activity_ue_distance_util);

        mContext = this;
        mapView = findViewById(R.id.mapview);
        mapView.onCreate(savedInstanceState);

        initMap();
        initView();

    }

    private void initMap() {
        mapView.addMapRenderCallback(new MapView.OnMapReadyListener() {
            @SuppressLint("RtlHardcoded")
            @Override
            public void onMapReady(MineMap oMineMap) {
                mineMap = oMineMap;
                mineMap.getUiSettings().setZoomControlsEnabled(false);
                mineMap.getUiSettings().setRotateGesturesEnabled(true);// 是否可以旋转地图
                mineMap.getUiSettings().setTiltGesturesEnabled(true);
                mineMap.getUiSettings().setLogoEnabled(true);
				mineMap.setStyleUrl(Config.mBaseUrl + Config.MAP_ID, new MineMap.OnStyleLoadedListener() {
					@Override
					public void onStyleLoaded(String s) {
						mineMap.setTrafficShow(false); //是否展示交通路况信息
					}
				});
                //设置指南针是否显示，默认是显示
                mineMap.getUiSettings().setCompassEnabled(true);
                mineMap.getUiSettings().setCompassGravity(Gravity.LEFT);
//                mineMap.getUiSettings().setCompassImage(getResources().getDrawable(R.mipmap.icon_compass));
                mineMap.getUiSettings().setCompassMargins(DensityUtil.dip2px(mContext, 11), DensityUtil.dip2px(mContext, 80),
                        0, 0);
                mineMap.setCameraPosition(
                        new CameraPosition.Builder().target(new LatLng(32.01627, 118.87309)).zoom(14)
                                .tilt(0)//设定倾斜角度
                                .bearing(0) //摄像机指向的方向,从北部顺时针方向设置
                                .build());
                mineMap.setMaxZoomPreference(17);//设置最高展示级别，最高为17级别
                mineMap.setMinZoomPreference(3);//设置最低的展示级别
				mineMap.addOnMapClickListener(DistanceUtilActivty.this);
                center = new LatLng(32.01627, 118.87309);

            }
        });

    }


    private void initView() {

    	value = findViewById(R.id.value);
        btn_distance = findViewById(R.id.btn_distance);
        btn_area = findViewById(R.id.btn_area);
		final ImageView zoomIn = findViewById(R.id.zoomin);
		final ImageView zoomOut = findViewById(R.id.zoomout);

        View.OnClickListener listener = new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (view.equals(zoomIn)) {

                	zoomIn(view);
				} else if (view.equals(zoomOut)) {

                	zoomOut(view);
				} else if (view.equals(btn_distance)) {

                    perfomMeasureDistance();
                } else if (view.equals(btn_area)) {

					perfomMeasureArea();
				}
            }
        };

		zoomIn.setOnClickListener(listener);
		zoomOut.setOnClickListener(listener);
        btn_distance.setOnClickListener(listener);
		btn_area.setOnClickListener(listener);

    }

	ArrayList<LatLng> listData = new ArrayList<>();
	private int type = 0;
    /**
     *
     */
    private void perfomMeasureDistance() {

		type = 1;
		value.setText("在地图上点击");
		if (listData.size()>0) {
			listData.clear();
			updateLayer();
		}
    }



	private void perfomMeasureArea() {

		type = 2;
		value.setText("在地图上点击");
		if (listData.size()>0) {
			listData.clear();
			updateLayer();
		}
	}

	//集中写一下几个变化方法
	private void updateLayer() {

		//线
		if (type == 1) {

			updatePolyLines(type);
			value.setText(caculateDistance()+"米");
		}
		//块
		if (type == 2) {

			updatePolygons();
			value.setText(caculateArea()/10E6+"平方公里");
		}
	}

	/**
	 * 计算距离
	 * @return
	 */
	private double caculateDistance() {

		double totalDistance = 0;
		if (listData.size() >= 2) {

			for (int i=0; i<listData.size()-1;i++) {

				double tempDistance = mineMap.distanceWithStartPoint(listData.get(i), listData.get(i+1));
				totalDistance += tempDistance;
			}
		}
		//保留1位小数
		BigDecimal b = new BigDecimal(totalDistance);
		totalDistance = b.setScale(1,BigDecimal.ROUND_HALF_UP).doubleValue();

		return totalDistance;
	}

	/**
	 * 算图形面积
	 * @return
	 */
	private double caculateArea() {
		double area = 0d;
		if (listData != null && listData.size() > 2) {
			LatLng[] list = new LatLng[listData.size()];
			for (int i = 0; i < listData.size(); i++) {
				list[i] = listData.get(i);
			}

			area = mineMap.polygonAreaWithCoordinates(list);  //亩为单位
		}
		return area;
	}



	Polyline mPolyline;
	private void updatePolyLines(int type) {

		if (mPolyline != null) {
			mineMap.removePolyline(mPolyline);
		}

		if (listData.size() > 0) {

			LatLng[] lines = pointToLine(listData);
			if (type == 1)
				mPolyline = mineMap.addPolyline(new PolylineOptions()
						.add(lines)
						.width(3)
						.color(Color.BLUE));
			else
				mPolyline = mineMap.addPolyline(new PolylineOptions()
						.add(lines)
						.width(3)
						.color(Color.RED));

		}
	}


	//画面，把各个点链接起来
	Polygon m_polygon;
	private void updatePolygons() {

		if (m_polygon != null){
			mineMap.removePolygon(m_polygon);
		}


		m_polygon  = mineMap.addPolygon(new PolygonOptions().addAll(listData)
				.fillColor(Color.argb(10,0,206,209))
				.strokeColor(Color.argb(100,0,255,255))
		);
		//添加一个外框
//		strokeLines();
	}

	public void addPolygon(View view) {
//		LatLng[] lines = new LatLng[]{RandomUtil.randomLatLon(), RandomUtil.randomLatLon(), RandomUtil.randomLatLon()};
//		Polygon polygon = mineMap.addPolygon(new PolygonOptions()
//				.add(lines)
////                .info("多边形面啊啊啊啊啊啊啊")
//				.fillColor(RandomUtil.randomColor())
//				.alpha(0.5f)
//				.strokeColor(RandomUtil.randomColor()));
//		if (polygons == null) {
//			polygons = new ArrayList<>();
//		}
//		polygons.add(polygon);
	}



	Polyline m_polyline;
	private void strokeLines() {

		if (m_polyline != null) {
			mineMap.removePolyline(m_polyline);
		}

		ArrayList<LatLng> mlistLineData = null;

		if (listData.size() > 0) {
			mlistLineData = new ArrayList<>();
			mlistLineData.addAll(listData);
			mlistLineData.add(listData.get(0));

			LatLng[] lines = pointToLine(mlistLineData);

			m_polyline = mineMap.addPolyline(new PolylineOptions()
					.add(lines)
					.width(3)
					.color(Color.GREEN));
		}
	}

	/**
	 * 点的集合转化成点的数组
	 * @param pointItems 点的集合
	 * @return 点的数组
	 */
	private LatLng[] pointToLine(ArrayList<LatLng> pointItems) {
		LatLng[] lines;
		if(pointItems!=null&&pointItems.size()>0){
			lines=new LatLng[pointItems.size()];
			for (int i = 0; i < pointItems.size(); i++) {
				lines[i]=pointItems.get(i);
			}
			return lines;
		}
		return null;
	}

	@Override
	public void onMapClick(@NonNull LatLng latLng) {

		listData.add(latLng);
		updateLayer();
	}



    public void zoomIn(View view) {
		if (mineMap != null) {
			mineMap.moveCamera(CameraUpdateFactory.zoomIn());
		}
	}

	public void zoomOut(View view) {
		if (mineMap != null) {
			mineMap.moveCamera(CameraUpdateFactory.zoomOut());
		}
	}


    //地图生命周期
    @Override
    protected void onStart() {
        super.onStart();
        if (mapView != null)
            mapView.onStart();
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mapView != null)
            mapView.onStop();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mapView != null)
            mapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mapView != null)
            mapView.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mapView != null)
            mapView.onDestroy();
    }


}
